Imports System.Windows.Forms

Public Class frmImportLSPC

    Private dictLSPCParameters As Generic.Dictionary(Of String, String)
    Private dgvStations As WRDB.Controls.DGVEditor
    Private dgvParameters As WRDB.Controls.DGVEditor

    Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
        Me.DialogResult = System.Windows.Forms.DialogResult.OK
        Me.Close()
    End Sub

    Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click
        Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.Close()
    End Sub

    Private Sub chkFilter_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkFilter.CheckedChanged, txtThreshDev.TextChanged
        tblFilter.Enabled = chkFilter.Checked
        lblFiltering.Text = String.Format("Filtering: {0}", IIf(chkFilter.Checked, String.Format("{0}% threshold", txtThreshDev.Text), "Off"))
    End Sub

    Private Sub frmImportLSPC_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        For i As Integer = 1 To 2
            Dim dg As DataGridView = Choose(i, dgStations, dgParameters)
            For Each r As DataRow In dg.DataSource.Rows
                Dim KeyPrefix As String = Choose(i, "Stations\", "Parameters\") & r.Item(1)
                SaveSetting(REGAPP, Name, KeyPrefix & "\Checked", r.Item(0))
                SaveSetting(REGAPP, Name, KeyPrefix & "\Mult", r.Item(2))
                SaveSetting(REGAPP, Name, KeyPrefix & "\Convert", r.Item(3))
            Next
            UpdateLabels(dg)
        Next
        SaveSetting(REGAPP, Name, "StartDate", dtStart.Value.ToString(System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat))
        SaveSetting(REGAPP, Name, "EndDate", dtEnd.Value.ToString(System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat))
        SaveSetting(REGAPP, "ImportFilter", "FilterChecked", chkFilter.Checked)
        SaveSetting(REGAPP, "ImportFilter", "ThreshDev", txtThreshDev.Text)
    End Sub

    Private Sub frmImportLSPC_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        For i As Integer = 1 To 2
            Dim dg As DataGridView = Choose(i, dgStations, dgParameters)
            For Each r As DataRow In dg.DataSource.Rows
                Dim KeyPrefix As String = Choose(i, "Stations\", "Parameters\") & r.Item(1)
                Dim s As String = GetSetting(REGAPP, Name, KeyPrefix & "\Convert", "")
                Dim m As String = GetSetting(REGAPP, Name, KeyPrefix & "\Mult", "1.0")
                If s <> "" Then
                    r.Item(0) = GetSetting(REGAPP, Name, KeyPrefix & "\Checked", False)
                    r.Item(2) = IIf(IsNumeric(m) AndAlso m = 1.0, "1.0", m)
                    r.Item(3) = s.ToUpper
                End If
            Next
            UpdateLabels(dg)
        Next
        dtStart.Format = System.Windows.Forms.DateTimePickerFormat.Custom
        dtStart.CustomFormat = MyDateFormat()
        dtEnd.Format = System.Windows.Forms.DateTimePickerFormat.Custom
        dtEnd.CustomFormat = MyDateFormat()
        dtStart.Value = GetSetting(REGAPP, Name, "StartDate", MyCDate(dtStart.MinDate))
        dtEnd.Value = GetSetting(REGAPP, Name, "EndDate", MyCDate(dtEnd.MaxDate))
        chkFilter.Checked = GetSetting(REGAPP, "ImportFilter", "FilterChecked", False)
        txtThreshDev.Text = GetSetting(REGAPP, "ImportFilter", "ThreshDev", "10")
    End Sub

    Private Sub ContextMenuStrip1_ItemClicked(ByVal sender As Object, ByVal e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles ContextMenuStrip1.ItemClicked
        With CType(CType(CType(sender, ContextMenuStrip).SourceControl, DataGridView).DataSource, DataTable)
            For Each r As DataRow In .Rows
                r.Item(0) = e.ClickedItem Is CheckAllToolStripMenuItem
            Next
        End With
        UpdateLabels(CType(sender, ContextMenuStrip).SourceControl)
    End Sub

    Friend Sub Initialize(lstStations As Generic.List(Of String), dictParameters As Generic.Dictionary(Of String, String))
        dictLSPCParameters = dictParameters
        Dim dtStations As New DataTable
        Dim dtParameters As New DataTable

        For i As Integer = 1 To 2
            Dim dt As DataTable = Choose(i, dtStations, dtParameters)
            Dim lst As Generic.List(Of String) = Nothing
            If i = 1 Then
                lst = lstStations
            Else
                lst = New Generic.List(Of String)
                For Each p As String In dictParameters.Keys
                    lst.Add(p)
                Next
            End If
            Dim dg As DataGridView = Choose(i, dgStations, dgParameters)

            '4 columns are: import checkbox, source station/parameter name, muliplier (hidden for stations), conversion Station_ID/PCode

            With dt
                .Columns.Add("Import", GetType(Boolean))
                .Columns.Add(Choose(i, "Station", "Parameter") & " Name", GetType(String))
                .Columns.Add("Multiplier", GetType(String))
                .Columns.Add("Convert To", GetType(String))
                For Each s As String In lst
                    .Rows.Add(True, s, 1.0, s)
                Next
            End With
            With dg
                .DataSource = dt
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                .AllowUserToOrderColumns = False
                .AllowUserToResizeColumns = False
                .AllowUserToResizeRows = False
                For j As Integer = 1 To 4
                    With .Columns(j - 1)
                        .SortMode = DataGridViewColumnSortMode.NotSortable
                        .AutoSizeMode = Choose(j, DataGridViewAutoSizeColumnMode.AllCells, DataGridViewAutoSizeColumnMode.AllCells, DataGridViewAutoSizeColumnMode.AllCells, DataGridViewAutoSizeColumnMode.Fill)
                        .ReadOnly = Choose(j, False, True, False, False)
                        .DefaultCellStyle.ForeColor = Choose(j, Color.Black, Color.Gray, Color.Black, Color.Black)
                        .HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
                        .HeaderCell.Style.WrapMode = DataGridViewTriState.False
                        If j = 3 Then
                            .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                        End If
                    End With
                    .AutoResizeColumn(1, DataGridViewAutoSizeColumnMode.AllCells)
                Next
            End With
            dgStations.Columns(2).Visible = False 'don't show multiplier column
            UpdateLabels(Choose(i, dgStations, dgParameters))
        Next
        dgvStations = New WRDB.Controls.DGVEditor(dgStations)
        dgvParameters = New WRDB.Controls.DGVEditor(dgParameters)
    End Sub

    ''' <summary>
    ''' Return dictionary of selected stations where key is imported value and value is stationID to convert to
    ''' </summary>
    Friend Function SelectedStations() As Generic.Dictionary(Of String, String)
        Return SelectedItems(True)
    End Function

    ''' <summary>
    ''' Return dictionary of selected pcodes where key is imported value and value is PCode to convert to (selected parameter multipliers will be appended to PCode, tab delimited)
    ''' </summary>
    Friend Function SelectedParameters() As Generic.Dictionary(Of String, String)
        Return SelectedItems(False)
    End Function

    Private Function SelectedItems(Stations As Boolean) As Generic.Dictionary(Of String, String)
        Dim dict As New Generic.Dictionary(Of String, String)
        Dim dt As DataTable = IIf(Stations, dgStations.DataSource, dgParameters.DataSource)
        For Each r As DataRow In dt.Rows
            If r.Item(0) Then dict.Add(r.Item(1), r.Item(3) & IIf(Stations, "", vbTab & r.Item(2))) 'append multiplier for parameters
        Next
        Return dict
    End Function

    Private Sub dgParameters_CellValidated(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgParameters.CellValidated
        With CType(sender, DataGridView)
            If e.ColumnIndex = 2 Then 'multiplier
                With .Item(e.ColumnIndex, e.RowIndex)
                    If Not IsDBNull(.Value) Then
                        If IsNumeric(.Value) Then
                            '.Value = .Value.ToString("0.000")
                        Else
                            .Value = .Value.ToUpper
                        End If
                    Else
                        .Value = "1.0"
                    End If
                End With
            End If
        End With
    End Sub

    Private Sub dg_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgParameters.CellValueChanged, dgStations.CellValueChanged
        With CType(sender, DataGridView)
            If e.ColumnIndex = 0 Then 'update label
                UpdateLabels(sender)
            ElseIf e.ColumnIndex = 3 Then 'make ID all caps
                With .Item(e.ColumnIndex, e.RowIndex)
                    If Not IsDBNull(.Value) Then
                        .Value = .Value.ToUpper
                        .Value = Strings.Left(.Value, IIf(sender Is dgStations, 25, 10))
                    End If
                End With
            End If
        End With
    End Sub

    Private Sub dg_CurrentCellDirtyStateChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgParameters.CurrentCellDirtyStateChanged, dgStations.CurrentCellDirtyStateChanged
        With CType(sender, DataGridView)
            If .IsCurrentCellDirty Then .CommitEdit(DataGridViewDataErrorContexts.Commit)
        End With
    End Sub

    Private Sub UpdateLabels(ByVal dg As DataGridView)
        With dg
            Dim cnt As Integer = 0
            For r As Integer = 0 To .RowCount - 1
                If .Item(0, r).Value Then cnt += 1
            Next
            If dg Is dgStations Then
                lblNumStations.Text = "Stations Selected: " & cnt
            Else
                lblNumPCodes.Text = "Parameters Selected: " & cnt
            End If
        End With
    End Sub

    Private Sub lnkSelectAll_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lnkSelectAll.LinkClicked
        dtStart.Value = dtStart.MinDate
        dtEnd.Value = dtEnd.MaxDate
    End Sub

    Private Sub dtStart_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtStart.ValueChanged, dtEnd.ValueChanged
        lblDates.Text = String.Format("Date Range: {0:d} to {1:d}", dtStart.Value, dtEnd.Value)
    End Sub

    Private Sub btnSelectAllSta_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSelectAllSta.Click, btnSelectNoneSta.Click, btnSelectAllPCode.Click, btnSelectNonePCode.Click
        Dim dg As DataGridView = IIf(sender Is btnSelectAllSta Or sender Is btnSelectNoneSta, dgStations, dgParameters)
        With CType(dg.DataSource, DataTable)
            For Each r As DataRow In .Rows
                r.Item(0) = sender Is btnSelectAllSta Or sender Is btnSelectAllPCode
            Next
        End With
        UpdateLabels(dg)
    End Sub

    Private Sub btnJournal_Click(sender As System.Object, e As System.EventArgs) Handles btnJournal.Click
        frmJournal.GetJournalDescription()
    End Sub

    Private Sub dgParameters_SelectionChanged(sender As Object, e As System.EventArgs) Handles dgParameters.SelectionChanged
        btnConstant.Visible = False
        With dgParameters
            If .SelectedCells.Count = 1 Then
                lblParameterInfo.Text = "LSPC Description: " & Proper(dictLSPCParameters(.Item(1, .SelectedCells(0).RowIndex).Value))
                If .CurrentCell.ColumnIndex = 2 Then btnConstant.Visible = True
            Else
                lblParameterInfo.Text = ""
            End If
        End With
    End Sub

    Private Sub ContextMenuConstants_ItemClicked(sender As Object, e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles mnuEnglishToMetric.DropDownItemClicked, mnuMetricToEnglish.DropDownItemClicked, mnuOther.DropDownItemClicked
        With dgParameters
            .CurrentCell.Value = e.ClickedItem.ToolTipText
        End With
    End Sub

    Private Sub btnConstant_Click(sender As System.Object, e As System.EventArgs) Handles btnConstant.Click
        ContextMenuConstants.Show(btnConstant, 0, btnConstant.Height)
    End Sub
End Class
